<template>
  <div class="lastBox">
    <h3>发表评论</h3>
    <hr />
    <textarea placeholder="请输入你要哔哔的内容(最多输入120字)" v-model="msg"></textarea>
    <mt-button type="primary" size="large" @click="postComments">发表</mt-button>
    <div class="content" v-for="(item,index) in Arr" :key="index">
      <div class="first">第{{ index+1 }}楼 &nbsp;发表人: {{ item.user_name }} &nbsp;&nbsp; 发表时间:{{ item.add_time | deteFoemat }}</div>
      <div class="lasts">{{ item.content==""?"该用户很懒什么都没写":item.content }}</div><!-- 判断获取到的数据是否为空,当为空时则输出"该用户很懒什么都没写" -->
    </div>
    <mt-button type="primary" size="large" plain @click="getMore">查看更多</mt-button>
  </div>
</template>
<script>
import { Toast } from 'mint-ui';
export default {
  data() {
    return {
      page: 1,
      Arr: [],
      //对用户输入的内容进行双向绑定
      msg: ""
    };
  },
  created() {
    this.getCOmments();
  },
  //接收父组件中的id
  props: ["id"],
  methods: {
    getCOmments() {
      //获取评论
      this.axios
        .get("api/getcomments/" + this.id + "?pageindex=" + this.page)
        .then(res => {
          console.log(res.data.message);
          //因为每次都是获取的10页所以后面通过concat将点击后获取的10条数据拼接上去,并不会覆盖
          this.Arr = this.Arr.concat(res.data.message);
        });
    },
    getMore() {
      //加载更多 每当点击加载更多的时候获取的页数为第二页
      this.page++;
      this.getCOmments();
    },
    postComments() {
        //判断是否为空
      if (this.msg.trim() == "") {
          return Toast("数据不能为空")
      }
      //获取内容将内容通过unshift添加到评论的最前面
      this.axios
        .post("api/postcomment/" + this.id, { content: this.msg })
        .then(res => {
            this.Arr.unshift({
                use_name: "匿名用户",
                add_time: new Date(),
                content: this.msg
            })
            this.msg=""
        });
    }
  }
};
</script>
<style lang="less" scoped>
.lastBox {
  h3 {
    font-size: 18px;
  }
  textarea {
    margin: 0;
  }
  .content {
    font-size: 15px;
    padding: 5px 0;
    .first {
      width: 100%;
      padding: 5px;
      background-color: pink;
    }
    .lasts {
      text-indent: 2em;
      width: 100%;
      padding: 5px;
      background-color: yellow;
    }
  }
}
</style>